package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/openai/openai-go"
	"github.com/smash-llj/Nexa-server/global"
	"github.com/smash-llj/Nexa-server/models"
)

// BuildChatList 构建聊天
func BuildChatList(HistoryList []models.AIMessage) []openai.ChatCompletionMessageParamUnion {
	ChatList := []openai.ChatCompletionMessageParamUnion{
		openai.SystemMessage("你的名字叫小爱，你是一个聪明的助手。"),
		openai.SystemMessage("如果别人询问你是不是chatgpt,请记住你的名字是小爱。"),
		openai.SystemMessage("同时你也是一个代码高手，请尽全力帮询问者解答问题，详细一点。"),
	}

	// 添加历史聊天记录
	for _, item := range HistoryList {
		switch item.Type {
		case 1:
			ChatList = append(ChatList, openai.UserMessage(item.Content))
		default:
			ChatList = append(ChatList, openai.AssistantMessage(item.Content))
		}
	}
	return ChatList
}

// FindMessageHistoryList 查询历史消息
func FindMessageHistoryList(sessionId string) ([]models.AIMessage, error) {
	var res []models.AIMessage
	if err := global.DB.Model(&models.AIMessage{}).Where("session_id = ?", sessionId).Find(&res).Error; err != nil {
		return nil, fmt.Errorf("查询历史消息失败: %v", err)
	}
	return res, nil
}

// SaveRecordMessage 记录消息到数据库
func SaveRecordMessage(content, sessionId string, messageType int) error {
	message := models.AIMessage{
		Type:      messageType,
		Content:   content,
		SessionId: sessionId,
	}
	// 创建消息记录
	if err := global.DB.Create(&message).Error; err != nil {
		return fmt.Errorf("创建消息失败: %v", err)
	}
	return nil
}

// AskChat 询问Ai
func AskChat(ctx *gin.Context, List []openai.ChatCompletionMessageParamUnion, sessionId string) bool {
	// 初始化流式请求
	stream := global.AiClient.Chat.Completions.NewStreaming(ctx, openai.ChatCompletionNewParams{
		Messages: List,
		Model:    openai.ChatModelGPT4o,
	})

	var fullContent string
	for stream.Next() {
		chunk := stream.Current()
		if len(chunk.Choices) > 0 {
			content := chunk.Choices[0].Delta.Content
			fmt.Println(chunk)
			fullContent += content
			// 响应客户端并刷新缓冲区
			if _, err := fmt.Fprintf(ctx.Writer, "%s", content); err != nil {
				fmt.Printf("写入客户端错误：%v\n", err)
				return false
			}
			ctx.Writer.Flush()
		}
	}

	// 检查流错误
	if err := stream.Err(); err != nil {
		fmt.Printf("流处理错误：%v\n", err)
		return false
	}

	// 保存 AI 回应并返回成功状态
	if err := SaveRecordMessage(fullContent, sessionId, global.AIMessageAI); err != nil {
		fmt.Printf("保存消息失败：%v\n", err)
		return false
	}

	return true
}
